package com.coisini.controller.admin;

import com.coisini.result.Result;
import com.coisini.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口，文件上传
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) throws IOException {
        log.info("文件上传：{}", file);

        //获取文件的原始名字
        String originalFilename = file.getOriginalFilename();
        //获取原始拓展名
        //从原始文件的最后一个 . 开始往后截取
        String   extention = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成新的文件名
        String objectName = UUID.randomUUID().toString() + extention;

        //调用工具类方法
        String filePath = aliOssUtil.upload(file.getBytes(), objectName);

        System.out.println(filePath);
        //返回文件的访问路径
        return Result.success(filePath);
    }
}
